<?php

namespace app\admin\controller\pt;

use app\common\controller\Backend;
use think\Db;

/**
 * 机构汇款
 *
 * @icon fa fa-circle-o
 */
class AgencyRemit extends Backend
{

    /**
     * AgencyRemit模型对象
     * @var \app\admin\model\pt\AgencyRemit
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\pt\AgencyRemit;
        $remitTypeList = $this->model->getRemitTypeList();
        $this->view->assign("remitTypeList", $remitTypeList);
        $orderTypeList = $this->model->getOrderTypeList();
        $this->view->assign("orderTypeList", $orderTypeList);
    }




    /**
     * 查看
     *
     * @return string|Json
     * @throws \think\Exception
     * @throws DbException
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if (false === $this->request->isAjax()) {
            return $this->view->fetch();
        }
        //如果发送的来源是 Selectpage，则转发到 Selectpage
        if ($this->request->request('keyField')) {
            return $this->selectpage();
        }
        [$where, $sort, $order, $offset, $limit] = $this->buildparams();
        $list = $this->model
            ->with(["remitOrders"])
            ->where($where)
            ->order($sort, $order)
            ->paginate($limit);
        $result = ['total' => $list->total(), 'rows' => $list->items()];
        return json($result);
    }


    /**
     * 添加
     *
     * @return string
     * @throws \think\Exception
     */
    public function add()
    {
        if (false === $this->request->isPost()) {
            return $this->view->fetch();
        }
        $this->modelValidate = true;
        $params = $this->request->post('row/a');
        if (empty($params)) {
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $params = $this->preExcludeFields($params);

        if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
            $params[$this->dataLimitField] = $this->auth->id;
        }
        $params['remit_no'] = trim($params['remit_no']);
        $remitOrders = $params['remit_orders'];
        $remitOrders = (array) json_decode($remitOrders, true);
        $amount = $params['amount'];
        //检查金额是否有效
        if (empty($amount) || $amount <= 0) {
            $this->error('请输入有效金额');
        }
        //检查机构名称
        if (empty($params['agency_name'])) {
            $this->error('请输入机构名称');
        }

        //检查汇款单号
        if (empty($params['remit_no'])) {
            $this->error('请输入汇款单号');
        }
        // 验证工作明细数据
        $this->validateRemitOrders($remitOrders, null, $amount);

        Db::startTrans();
        try {
            $this->model->validateFailException(true)->validate(
                ['remit_no' => ['unique' => 'pt_agency_remit,remit_no']],
                ['remit_no.unique' => '汇款单号已经存在']
            );

            $this->model->allowField(true)->save($params);

            // 👇 关键：手动判断 saveAll 返回值
            $this->model->remitOrders()->saveAll($remitOrders);

            Db::commit();
        } catch (\Exception $e) {
            Db::rollback();
            $this->error('err:' . $e->getMessage());
        }
        $this->success('添加成功');
    }


    /**
     * 验证工作明细数据
     * 
     * @param array $remitOrders 汇款订单数组
     * @param int $remitId 汇款ID
     * @return void
     * @throws \think\exception\HttpException
     */
    private function validateRemitOrders($remitOrders, $remitId, $amount)
    {
        $order_ids = [];
        $sum = 0;
        foreach ($remitOrders as $k => &$v) {
            if (!empty($remitId)) {
                $v['remit_id'] = $remitId;
            }

            // 验证订单编号
            $v['order_id'] = trim($v['order_id']);
            if (in_array($v['order_id'], $order_ids)) {
                $this->error('关联订单id【' . $v['order_id'] . '】不能重复');
            }

            $sum += $v['amount'];

        }
        //检查汇款金额与订单分配总金额是否一致
        if ($sum != $amount) {
            $this->error('汇款金额与订单分配总金额不一致,请检查订单金额');
        }
    }
    /**
     * 获取订单列表（用于弹窗选择）
     */
    public function getOrderList()
    {
        $orderType = $this->request->param('order_type', '');
        $keyword = $this->request->param('keyword', '');

        if (empty($orderType)) {
            $this->error('请选择订单类型');
        }

        $page = $this->request->param('page', 1);
        $limit = $this->request->param('limit', 10);

        // 根据订单类型查询不同的表
        $tableName = $this->getTableNameByOrderType($orderType);
        if (empty($tableName)) {
            $this->error('不支持的订单类型');
        }

        $where = [];
        if (!empty($keyword)) {
            $where['user_name'] = ['like', '%' . $keyword . '%'];
        }

        $list = Db::name($tableName)
            ->where($where)
            ->field('id,user_name,order_no')
            ->order('id asc')
            ->page($page, $limit)
            ->select();

        $total = Db::name($tableName)->where($where)->count();

        $this->success('获取成功', null, [
            'list' => $list,
            'total' => $total,
            'page' => $page,
            'limit' => $limit
        ]);
    }

    /**
     * 根据订单类型获取表名
     */
    private function getTableNameByOrderType($orderType)
    {
        $tableMap = [
            '1' => 'pt_order', // 职称
            '2' => 'pt_edu_cont_order', // 继续教育
            '3' => 'pt_patent_order', // 专利
            '4' => 'pt_softbook_order', // 软著
            '5' => 'pt_sci_res_order', // 科研
            '6' => 'pt_paper_order', // 论文
            '7' => 'pt_edu_order' // 学历

        ];

        return $tableMap[$orderType] ?? '';
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */


}
